package com.zyf.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyf.listener.DictListener;
import com.zyf.mapper.DictMapper;
import com.zyf.model.cmn.Dict;
import com.zyf.service.DictService;
import com.zyf.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zyf
 * @date 2021年04月30日 16:41
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    /**
     * 根据上级id获取子节点数据列表
     * @author zyf
     * @date 2021/5/6 11:06
     * @param id
     * @return java.util.List<com.zyf.model.cmn.Dict>
     */
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dicts = baseMapper.selectList(wrapper);
        //判断有没有子节点并设置给HasChildren
        dicts.forEach(dict -> {
            Long dictId = dict.getId();
            Boolean children = this.isChildren(dictId);
            dict.setHasChildren(children);
        });
        return dicts;
    }

    /**
     * 导出数据字典到excel中
     * @author zyf
     * @date 2021/5/6 14:06
     * @param response
     */
    @Override
    public void exportDict(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //这里URLEncoder.encode可以防止中文乱码
        String fileName = null;
        try {
            fileName = URLEncoder.encode("数据字典", StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");

        List<Dict> dictList = baseMapper.selectList(null);

        ArrayList<DictEeVo> DictEeVoList = new ArrayList<>();
        dictList.forEach(dict -> {
            DictEeVo dictEeVo = new DictEeVo();
            /*dictEeVo.setId(dict.getId())
                    .setParentId(dict.getParentId())
                    .setName(dict.getName())
                    .setValue(dict.getValue())
                    .setDictCode(dict.getDictCode());*/
            //copy dict对象到dictEeVo  相当于上面的注释内容
            if (dict != null) {
                BeanUtils.copyProperties(dict,dictEeVo);
            }
            DictEeVoList.add(dictEeVo);
        });

        //调用方法执行写操作
        try {
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("dict").doWrite(DictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * excel导入数据字典到数据库中
     * @author zyf
     * @date 2021/5/6 15:05
     * @param file
     */
    @Override
    @CacheEvict(value = "dict",allEntries = true) //
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据dictcode和value查询name
     * @author zyf
     * @date 2021/5/10 17:01
     * @param dict
     * @return java.lang.String
     */
    @Override
    public String getDictName(String dictCode, String value) {
        if (StringUtils.isEmpty(dictCode)){ //如果dictcode为空根据value查询name
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict selectOne = baseMapper.selectOne(wrapper);
            return selectOne.getName();
        }else {//如果dictcode为不为空根据value查询name
            //根据dictcode查询dict对象，根据dictCode和value查询
            Dict byDictCode = this.getDictByDictCode(dictCode);
            Long paret_id = byDictCode.getId();
            QueryWrapper<Dict> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("parent_id",paret_id);
            wrapper2.eq("value",value);
            Dict selectOne2 = baseMapper.selectOne(wrapper2);
            return selectOne2.getName();
        }

    }


    /**
     * 根据dictCode查询下级节点
     * @author zyf
     * @date 2021/5/10 18:25
     * @param dictCode  数据字典编码
     * @return java.util.List<com.zyf.model.cmn.Dict>
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode数据字典编码得到 数据字典
        Dict dict = this.getDictByDictCode(dictCode);

        //根据id查询子节点
        List<Dict> dictList = this.findChildData(dict.getId());
        return dictList;
    }

    /**
     * 根据dictCode数据字典编码得到 数据字典
     * @author zyf
     * @date 2021/5/10 18:33
     * @param dictCode 数据字典编码
     * @return com.zyf.model.cmn.Dict
     */
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return dict;
    }
    /**
     * 根据id判断数据下有没有子节点
     * @author zyf
     * @date 2021/5/6 11:17
     * @param id 数据字典 id
     * @return java.lang.Boolean
     */
    private Boolean isChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}
